package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@WebServlet("/download.do")
public class DownloadServlet extends HttpServlet {

    private static final long serialVersionUID = 3L;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = request.getParameter("f");
        File file = new File("d:/tmp/img/"+fileName);
        if (file.exists()) {
            response.setContentType("application/octet-stream");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            InputStream is = new FileInputStream(file);
            OutputStream os = response.getOutputStream();
            byte[] arr = new byte[1024];
            int len = 0;
            while ((len = is.read(arr)) != -1) {
                os.write(arr, 0, len);
            }
            is.close();
            os.close();
        }else {
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().write("文件不存在！");
        }
    }
}